﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq; // 用于 LINQ to XML
//using Newtonsoft.Json.Linq; // 用于 JSON 查询
namespace MainApplication.BaseLerning
{
    public class QueryByLINQ
    {
        public static String getData()
        {
            String result_str = "";
            //1.数据源：
            int[] nums = { 11, 2, 13, 34, 45, 16, 37, 18, 99 };
            List<Person> peoples = new List<Person>
            {
                new Person { Name = "Alice", Age = 15, City = "Beijing" },
                new Person { Name = "Bob", Age = 10, City = "Shanghai" },
                new Person { Name = "Charlie", Age = 35, City = "Beijing" },
                new Person { Name = "Tom", Age = 16, City = "Shanghai" }
            };
            //2、创建查询：
            //2.1 查询表达式语法：
            {
                var query1 =
                    from n in nums
                    where n % 2 == 0
                    select n;
                //2.2 方法语法：
                var query2 = nums
                    .Where(x => x % 2 == 0)
                    .Select(x => x)
                    .OrderByDescending(x => x);

                // 查询北京的成年人
                var beijingAdults = peoples
                      .Where(p => p.City == "Beijing" && p.Age >= 18)
                      .Select(p => new { p.Name, p.City });

                // 分组查询
                var grouped = peoples.GroupBy(p => p.City)
                                    .Select(g => new { City = g.Key, Count = g.Count() });
            }

            //定义一个查询（使用方法语法）：查找所有不是北京的未成年人
            var beijingAdults1 = peoples
                .Where(p => p.City != "Beijing" && p.Age < 18)
                .Select(p => p);
      
            //3. 执行查询··并处理查询结果
            foreach (var n in beijingAdults1)
            {
                result_str += "\n您要找的人是： " + n;
            }
            return result_str;
        }
    }

    public class YoungPerson
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string City { get; set; }
    }
}
